import { useRequest } from "@umijs/hooks";
import {Button, Cascader, Form, Input, message, Select} from 'antd';
import { Store } from 'rc-field-form/lib/interface';
import {getSecretString} from "../../../utils/encrypt";
import React, { useEffect, useState } from 'react';
import { fetchRequest } from "../../../utils/Request";
import { url } from "../../../utils/url";


export default function AddEquipment(props:any) {

    interface SearchParam {
        "index":number,
        "len":number,
        "orzName":String
    }

    interface RequestAddres {
        level: number,
        parentID: string,
        "addrArray": string[]
    }


    interface AddParam{
        "collegeAreaId": String,
        "building": String,
        "unit": String,
        "devName":String,
        "devLocation":String,
        "attrIDs":number[],
        "deviceModelID":number,
        "serialNo":String,
        "gateway":String
    }

    interface RegisterParam{
        "model":number,
        // "factory": String,
        // "type": String,
        "serialNo": String,
        "gateway":String
    }

    const layout = {
        labelCol: { span: 4 },
        wrapperCol: { span: 20 },
    };
    const tailLayout = {
        wrapperCol: { offset: 4, span: 14 },
    };

    const [form] = Form.useForm()

    const { Option } = Select;

    //搜索公司状态
    const [orzList, setOrzList] = useState<any>([]);
    const [devAttrList, setDevAttrList] = useState<any>([]);
    const [devTypeList, setDevTypeList] = useState<any>([]);

    const orzOptions = orzList.map((d:any,index:number) => <Option value={d.label} key={index}>{d.value}</Option>);
    const attrOptions = devAttrList.map((d:any,index:number) => <Option value={d.label} key={index} disabled={d.disable}>{d.value}</Option>);
    const typeOptions = devTypeList.map((d:any,index:number) => <Option value={d.value} key={index}>{d.title}</Option>);

    //盒子设备选项是否可见
    const[boxDevFlag,setBoxDevFlag] = useState<boolean>(false);
    const[boxDevGatewayFlag,setBoxDevGatewayFlag] = useState<boolean>(false);
    const[boxDevdeviceMac,setBoxDevdeviceMac] = useState<boolean>(false);

    const boxDevStyleVisible = {
        display:boxDevFlag?'':'none'
    };
    const deviceMacVisible = {
        display:boxDevdeviceMac?'':'none'
    }
    const boxDevGatewayStyleVisible = {
        display:boxDevGatewayFlag?'':'none'
    };

    const [boxDevTypeList, setBoxDevTypeList] = useState<any>([]);


    useEffect(() => {
        getDevTypeRequest();
    },[]);


    //搜索公司
    async function searchOrzRequest(params: SearchParam) {

        try {
            const json = await fetchRequest(url.SEARCH_ORZ, params);
            if (json.success) {
                setOrzList(json.data);
            } else {
                message.destroy();
                message.error(json.error)
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message)
        }
    }

    const searchOrz = useRequest(searchOrzRequest, {
        manual: true,
        loadingDelay: 200
    });

    //获取设备属性
    async function getDevAttrRequest(params:any) { 

        try {
            const json = await fetchRequest(url.GET_ATTRBYMODEI, params);
            if (json.success) {
                let devAttrListTemp = json.data;
                for(let i=0;i<devAttrListTemp.length;i++){
                    devAttrListTemp[i].disable=false;
                }
                // console.log(devAttrListTemp)
                setDevAttrList(devAttrListTemp);
            } else {
                message.destroy();
                message.error(json.error)
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message)
        }
    }

    const getDevAttr = useRequest(getDevAttrRequest, {
        manual: true,
        loadingDelay: 200
    });

    //获取设备类型
    async function getDevTypeRequest() {

        try {
            const json = await fetchRequest(url.GET_DEV_TYPE, "");
            if (json.success) {
                // console.log(json.data.children);
                setDevTypeList(json.data[0].children)
            } else {
                message.destroy();
                message.error(json.error)
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message)
        }
    }

    const getDevType = useRequest(getDevTypeRequest, {
        manual: true,
        loadingDelay: 200
    });

    //获取盒子设备厂家型号
    async function getBoxDevFactoryRequest() {

        try {
            const json = await fetchRequest(url.GET_BOX_DEV_FACTORY, '');
            if (json.success) {
               setBoxDevTypeList(json.data);
            } else {
                message.destroy();
                message.error(json.error)
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message)
        }
    }

    const getBoxDevFactory = useRequest(getBoxDevFactoryRequest, {
        manual: true,
        loadingDelay: 200
    });

    //注册新盒子
    async function deviceRegisterRequest(params: RegisterParam) {

        try {
            const json = await fetchRequest(url.DEVICE_REGISTER, params);
            if (json.success) {
                form.setFieldsValue({devCode:json.results});
                message.success("注册成功！");
            } else {
                message.destroy();
                message.error(json.error)
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message)
        }
    }

    const deviceRegister = useRequest(deviceRegisterRequest, {
        manual: true,
        loadingDelay: 200
    });

    //新增设备
    async function saveDevRequest(params: AddParam) {
        try {
            const json = await fetchRequest(url.ADD_MODIFY_DE, params);
            if (json.success) {
                message.destroy();
                message.success(json.message?"新增成功！" + json.message:'新增成功');
                props.addSuccess();
            } else {
                message.destroy();
                message.error(json.error)
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message)
        }
    }

    const saveDev = useRequest(saveDevRequest, {
        manual: true,
        loadingDelay: 200
    });


    function  handleChange(value:string) {
        // console.log(value)
    }

    function attrOnChange(value:any) {
        setBoxDevdeviceMac(false)
        const devAttrListTemp =[...devAttrList];
        for(let m=0;m<devAttrListTemp.length;m++){
                devAttrListTemp[m].disable=false;
        }
        if(value.indexOf(1) !== -1 || value.indexOf(9) !== -1){
            value.indexOf(9)!== -1 && setBoxDevdeviceMac(true)
            for(let j=0;j<devAttrListTemp.length;j++){
                if(devAttrListTemp[j].label===2 ){
                    devAttrListTemp[j].disable=true;
                }
            }
        }else if(value.indexOf(2) !== -1){
            for(let j=0;j<devAttrListTemp.length;j++){
                if(devAttrListTemp[j].label===1 ){
                    devAttrListTemp[j].disable=true;
                }
                if(devAttrListTemp[j].label===9 ){
                    devAttrListTemp[j].disable=true;
                }
            }
        }
        setDevAttrList(devAttrListTemp);
    }

    // function typeOnChange(value:any) {
    //
    //     setBoxDevFlag(false);
    //     setBoxDevGatewayFlag(false);
    //
    //     if(value === 14 || value === 12){
    //         //选择盒子设备时，显示盒子选项，并清空设备码，等待注册返回
    //         setBoxDevFlag(true);
    //         form.setFieldsValue({devCode:""});
    //         getBoxDevFactory.run();
    //
    //         if(value === 12){
    //             setBoxDevGatewayFlag(true);
    //         }
    //     }
    //     else{
    //         setBoxDevFlag(false);
    //         setBoxDevGatewayFlag(false);
    //     }
    //
    // }

    function typeOnChange(value:any) {
        getDevAttrRequest({deviceModelID:value})
        setBoxDevFlag(true);
        setBoxDevGatewayFlag(false);

        if(value === 12){
            setBoxDevGatewayFlag(true);
        }
        else{
            setBoxDevGatewayFlag(false);
        }

    }

    function boxDevOnChange(value:any) {
         // console.log(value)
    }

    function registerOnclick(){
        // console.log("点击注册")
        // console.log(form.getFieldsValue().boxDevSerial)

        if(form.getFieldsValue().devType==12){
            if(inputCheck(form.getFieldsValue().boxDevSerial) || inputCheck(form.getFieldsValue().boxDevGateway)||inputCheck(form.getFieldsValue().deviceName)){
                message.error("请完整填写后注册");
                return;
            }
        }
        else{
            if(inputCheck(form.getFieldsValue().boxDevSerial)){
                message.error("请完整填写后注册");
                return;
            }
        }

        const param = {
            model:form.getFieldsValue().devType,
            // factory: form.getFieldsValue().boxDev[0],
            // type: form.getFieldsValue().boxDev[1],
            serialNo: form.getFieldsValue().boxDevSerial,
            deviceName:form.getFieldsValue().devType==14?"":form.getFieldsValue().deviceName,
            gateway:form.getFieldsValue().devType==14?"":form.getFieldsValue().boxDevGateway
        }
        // console.log(param)
        deviceRegister.run(param);

    }

    // function register() {
    //     const param = {
    //         model:form.getFieldsValue().devType,
    //         factory: form.getFieldsValue().boxDev[0],
    //         type: form.getFieldsValue().boxDev[1],
    //         serialNo: form.getFieldsValue().boxDevSerial,
    //         gateway:form.getFieldsValue().devType==14?"":form.getFieldsValue().boxDevGateway
    //     }
    //     console.log(param)
    //     deviceRegister.run(param);
    // }

    function inputCheck(value:any) {
        return value === undefined || value === "";
    }

    //搜索
    function search(value:string) {
        // console.log(value);
        if(value ==="" || value===undefined){
            return
        }
        const params: SearchParam = {index:0, len:100, orzName:value};
        searchOrz.run(params);
    }

    function onFinish(value: Store) {

        if (value.dept.length>1){
            const params ={
                "collegeAreaId": value.dept[1],
                "building": value.dept[2],
                "unit": value.dept[3],
                "devName":value.devName,
                "devLocation":value.devLocation,
                "attrIDs":value.devAttr,
                "deviceModelID":value.devType,
                "serialNo":value.boxDevSerial,
                "gateway":value.boxDevGateway==undefined?"":value.boxDevGateway,
                "deviceMac":value.deviceMac
            }
            saveDev.run(params).then()
        }else {
            message.destroy();
            message.error('新增失败，设配地址请不要选择第一级')
        }

        // const params = {
        //     modelID:value.devType,
        //     serialNo:value.boxDevSerial,
        //     attrIDs:value.devAttr,
        //     devName:value.devName,
        //     devLocation:value.devLocation,
        //     orzID:value.dept,
        //     gateway:value.boxDevGateway==undefined?"":value.boxDevGateway
        // }


    }
    //

    const [addressNode,setAddressNode] = useState([])

    async function getAllAddressNode(params: RequestAddres) {
        try {
            const json = await fetchRequest(url.GET_ALL_ADDRESS_NODE, params);
            if (json.success) {
                console.log('getAllAddressNode:',json)
                setAddressNode(json.data)
                // return json.data
            } else {
                console.log('getAllAddressNode:',json)
                // return []
            }
        } catch (error:any) {
            console.log('getAllAddressNode:',error)
        }
    }
    const getAllAddress = useRequest(getAllAddressNode, {
        manual: true,
        loadingDelay: 200
    })

    async function getAllAdd(params: RequestAddres){
        try {
            const json = await fetchRequest(url.GET_ALL_ADDRESS_NODE, params);
            if (json.success) {
                // console.log('getAllAdd:',json)
                return json.data
            } else {
                // console.log('getAllAdd:',json)
                return []
            }
        } catch (error:any) {
            // console.log('error:',error)
        }
    }

    useEffect(()=> {
            getAllAddress.run({"level": 0, "parentID": "", "addrArray": ['']})
        }, []
    )

    const onChange =
        (value:any, selectedOptions:any) => {
    };

    const loadData =
        (selectedOptions:any) => {
        const targetOption = selectedOptions[selectedOptions.length - 1];
        targetOption.loading = true;
        let jsondata:any = [];
        let addrArray:any = [];
        selectedOptions.forEach(function (item:any){
            addrArray.push(item['value'])
        })
        getAllAdd({
            "level": targetOption['level']+1,
            "parentID": targetOption['value'],
            "addrArray": addrArray
        }).then((e:any)=>{jsondata = e})
        setTimeout(() => {
            targetOption.loading = false;
            targetOption.children = jsondata;
            setAddressNode([...addressNode])
        },1500);
    };
const filter=(inputValue:any,path:any[])=>{
    return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
}



    return (
        <Form form={form} {...layout} onFinish={onFinish}>

            <Form.Item label="设备名称" name="devName" rules={[{ required: true, message: "必须要输入设备名称!" }]}>
                <Input placeholder="请输入设备名称"/>
            </Form.Item>

            <Form.Item label="设备类型" name="devType" rules={[{ required: true, message: "必须要选择设备类型!" }]}>
                <Select
                    style={{ width: '100%' }}
                    placeholder="请选择设备类型"
                    onChange={typeOnChange}
                >
                    {typeOptions}
                </Select>
            </Form.Item>

            <Form.Item label="厂家主机序列号" name="boxDevGateway" style={boxDevGatewayStyleVisible} rules={[{ required: boxDevGatewayFlag, message: "必须要输入厂家主机序列号!" }]}>
                <Input  placeholder="请输入厂家主机序列号"/>
            </Form.Item>

            <Form.Item label="厂家出场序列号" name="boxDevSerial" style={boxDevStyleVisible} rules={[{ required: boxDevFlag, message: "必须要输入厂家出场序列号!" }]}>
                <Input placeholder="请输入厂家出场序列号"/>
            </Form.Item>

            <Form.Item label="设备属性" name="devAttr"  style={boxDevStyleVisible}  rules={[{ required: true, message: "必须要选择设备属性!" }]}>
                <Select
                    mode="multiple"
                    style={{ width: '100%' }}
                    placeholder="请选择设备属性"
                    onChange={attrOnChange}
                >
                    {attrOptions}
                </Select>
            </Form.Item>
            <Form.Item label="设备Mac编号" name="deviceMac" style={deviceMacVisible} rules={[{ required: boxDevdeviceMac, message: "必须要输入设备Mac编号!" }]}>
                <Input placeholder="请输入设备Mac编号"/>
            </Form.Item>
            <Form.Item label="设配地址" name="dept" rules={[{ required: true, message: "必须要选择设配地址!" }]}>
                <Cascader
                    changeOnSelect
                    showSearch={ { filter }}
                    placeholder="请输入设备地址"
                    options={addressNode}
                    loadData={loadData}
                    onChange={onChange}
                />
            </Form.Item>

            <Form.Item label="位置描述" name="devLocation" rules={[{ required: true, message: "必须要输入位置描述!" }]}>
                <Input  placeholder="请输入位置描述"/>
            </Form.Item>

            <Form.Item {...tailLayout}>
                <Button type="primary" htmlType="submit" loading={saveDev.loading}>提交</Button>
            </Form.Item>


        </Form>
    )
}
